#include "Switch.h"
#include "main.h"
#include "malloc.h"
#include "py32f0xx_hal_gpio.h"
#include "user_led.h"
#include "Model_info.h"
void Send_Switch_Response(uint8_t status);

Switch_Model_t sw_model;
Switch_Retry_t sw_retry;

void Set_LED_DO(uint8_t status);               //继电器指示灯
/// @brief 打开关闭继电器
/// @param status 状态
void OpenOFF_SW(uint8_t status)
{
	if(status==SW_ON)
	{
		HAL_GPIO_WritePin(SWITCH_OUT_GPIO_Port, SWITCH_OUT_Pin, GPIO_PIN_SET);
	}
	else if(status==SW_OFF)
	{
		HAL_GPIO_WritePin(SWITCH_OUT_GPIO_Port, SWITCH_OUT_Pin, GPIO_PIN_RESET);
	}
	sw_model.SW_OUT_Status=status;
	Send_Switch_Response(status);
	Set_LED_DO(status);
}

//打开关闭继电器指示灯
void Set_LED_DO(uint8_t status)
{
	if(status==SW_ON)
	{
		HAL_GPIO_WritePin(LED_DO_GPIO_Port, LED_DO_Pin, GPIO_PIN_SET);
	}
	else if(status==SW_OFF)
	{
		HAL_GPIO_WritePin(LED_DO_GPIO_Port, LED_DO_Pin, GPIO_PIN_RESET);
	}
}
void sw_sync_status(Switch_Protocol sw)
{
	//if(sw.status.sw_in!=sw_model.SW_OUT_Status)
	//{
		OpenOFF_SW(sw.status.sw_in);
	//}
	
	//SW_FB_Status(sw.status.relay_out);
}
/// @brief lora 开关数据接收函数
/// @param data 数据
/// @param len 数据长度
void Lora_Switch_Recive(uint8_t *data,uint8_t len)
{
	Switch_Protocol sw;
	if(len==sizeof(Switch_Protocol))
	{
		mymemcpy((uint8_t *)&sw,data,len);
		if(sw.id==model_info_handle.general_info.SN)
		{
			if(sw.type==SW_Control)
		  {
			  OpenOFF_SW(sw.status.sw_in);
		  }
		  else if(sw.type==SW_Response)
		  {
		  }
		  else if(sw.type==SW_Heartbeat)
		  {
			  Heartbeat_Receive();
			  sw_sync_status(sw);
		  }
			Updata_Heartbeat_Status();
	  }
	}
}
/******************************
 *发送继电器响应状态
******************************/
void Send_Switch_Response(uint8_t status)
{
	Switch_Protocol sw;
	sw.id=model_info_handle.general_info.SN;
	sw.status.relay_out=status;
	sw.type=SW_Response;
	User_LoRaSend_Data((uint8_t *)&sw,sizeof(Switch_Protocol));
}
/// @brief 发送开关控制状态
/// @param status 状态
void Send_Switch_Control(uint8_t status)
{
	Switch_Protocol sw;
	sw.id=model_info_handle.general_info.SN;
	sw.status.sw_in=status;
	sw.type=SW_Control;
	User_LoRaSend_Data((uint8_t *)&sw,sizeof(Switch_Protocol));
}
//用户接口，查询开关输入状态
uint8_t User_Get_Sw_status()
{
	return sw_model.SW_IN_Status;  
}
//用户查询继电器状态
uint8_t User_Get_Relay_status()
{
	return sw_model.SW_OUT_Status;
}
